import React, { useReducer,useContext } from "react";

const initailState = {
  a: 111,
  b: 2222,
};

const reduce = (proState, action) => {
    console.log(action.value);
    let newprops = {...proState}
  if (action.type === 'changea') {
    newprops.a = action.value
  }
  if (action.type === 'changeb') {
    newprops.b = action.value
}
  return newprops;
};

const GlobalContext = React.createContext();

export default function App() {
  const [state, dispatch] = useReducer(reduce, initailState);
  return (
    <GlobalContext.Provider value={{state,dispatch}}> // 传入公共服务
      <div>
        <h1>child</h1>
        <Child1 />
        <Child2 />
        <Child3 />
      </div>
    </GlobalContext.Provider>
  );
}

function Child1() {
    const { dispatch } = useContext(GlobalContext)  // 将对象值绑定到数据上面
  return (
    <div>
      <button onClick={() => {dispatch({type:'changea',value:'我是a的新数据'})}}>改变child2</button>
      <button onClick={() => {dispatch({type:'changeb',value:'我是b的新数据'})}}>改变child3</button>
    </div>
  );
}
function Child2() {
    const { state } = useContext(GlobalContext)  // 将对象值绑定到数据上面
  return <div>显示child2****** {state.a} </div>;
}
function Child3() {
    const { state } = useContext(GlobalContext)  // 将对象值绑定到数据上面
  return <div>显示child3 *********  {state.b}</div>;
}
